﻿using System.Collections.Generic;
using System.Web.Mvc;
using Olemas.DataModels;
using Olemas.Models;
using Olemas.ViewModels;

namespace Olemas.Controllers
{
    public class HomeController : Controller
    {
        private const int PageSize = 8;
        private HomeViewModel _homeViewModel;

        // Controllers

        //
        // GET: /Home/Ehitusteaduskond || GET: /Home/

        /// <summary>
        /// Returns the main view for the books.
        /// </summary>
        /// <param name="fac">The name of the faculty to load books for.</param>
        [OutputCache(Duration = 60)]
        public ActionResult Index(string fac)
        {
            var currentFacultyId = FacultyModel.GetFacultyId(fac);
            if (fac != null && currentFacultyId == 0)
            {
                return new HttpNotFoundResult();
            }
            var totalBooks = BookModel.GetNumberOfBooks(currentFacultyId);

            var totalPages = GlobalViewModel.GetTotalPages(totalBooks, PageSize);

            var pagesRemaining = GlobalViewModel.RemainingPages(totalPages, 1);

            _homeViewModel = new HomeViewModel(null, currentFacultyId, 1, totalPages, pagesRemaining);
            return View("Index", _homeViewModel);
        }

        /// <summary>
        /// Returns partial view of recentBooks to be updated with ajax.
        /// </summary>
        /// <param name="page">The page number to load books for.</param>
        /// <param name="facId">The Id of the faculty to load the books for.</param>
        /// <param name="ordering">What to order the books by.</param>
        public ActionResult RecentBooks(int page, int facId, string ordering)
        {
            var books = BookModel.GetBooks(facId, page, PageSize, ordering) as IEnumerable<Book>;

            var totalBooks = BookModel.GetNumberOfBooks(facId);

            var totalPages = GlobalViewModel.GetTotalPages(totalBooks, PageSize);

            var pagesRemaining = GlobalViewModel.RemainingPages(totalPages, page);

            _homeViewModel = new HomeViewModel(books, facId, page, totalPages, pagesRemaining);
            return PartialView("_RecentBooks", _homeViewModel);
        }
    }


}
